<template>
  <Dialog :title="t('studentPaper.view.title')" v-model="dialogVisible" width="950">
    <el-descriptions v-loading="formLoading" :column="1" border label-width="230">
      <el-descriptions-item :label="t('studentPaper.fields.studentCode')">
        <EditInput
          v-model="formData.studentCode"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.studentCode')"
          :disabled="true"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.studentName')">
        <EditInput
          v-model="formData.studentName"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.studentName')"
          :disabled="true"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.mentorName')">
        <UserSelect
          v-model="formData.mentorId"
          @selected="handleMentorSelected"
          :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.mentorName')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.paperTitle')">
        <EditInput
          v-model="formData.paperTitle"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.paperTitle')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.attachment')">
        <IMRUpload
          v-model="formData.attachment"
          :file-type="['pdf']"
          :file-size="20"
          :limit="1"
          :disabled="!edit"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.paperType')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_PAPER_TYPE"
          v-model="formData.paperType"
          :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.paperType')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.primaryAuthor')">
        <EditInput
          v-model="formData.primaryAuthor"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.primaryAuthor')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.personalRanking')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_PERSONAL_RANKING"
          v-model="formData.personalRanking"
          :placeholder="
            t('common.selectTextPlaceholder') + t('studentPaper.fields.personalRanking')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.personalRanking === '并列第一'"
        :label="t('studentPaper.fields.parallelCount')"
      >
        <EditInput v-model="formData.parallelCount" style="width: 150px">
          <template #prepend>{{ t('studentPaper.inputTips.parallelCountPrefix') }}</template>
          <template #append>{{ t('studentPaper.inputTips.parallelCountSuffix') }}</template>
        </EditInput>
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.personalRanking === '并列第一'"
        :label="t('studentPaper.fields.parallelRanking')"
      >
        <EditInput v-model="formData.parallelRanking" style="width: 150px">
          <template #prepend>{{ t('studentPaper.inputTips.parallelRankingPrefix') }}</template>
          <template #append>{{ t('studentPaper.inputTips.parallelRankingSuffix') }}</template>
        </EditInput>
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.casRanking')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_USTC_RANKING"
          v-model="formData.casRanking"
          :placeholder="
            t('common.selectTextPlaceholder') +
            t('studentPaper.fields.casRanking') +
            t('studentPaper.inputTips.casRanking')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.imrRanking')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_IMR_RANKING"
          v-model="formData.imrRanking"
          :placeholder="
            t('common.selectTextPlaceholder') +
            t('studentPaper.fields.imrRanking') +
            t('studentPaper.inputTips.casRanking')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.journalName')">
        <div class="flex w-1/1 gap-10px">
          <PositiveJournalSelect
            v-if="!manualInput"
            class="flex-grow-1"
            v-model="formData.journalId"
            :placeholder="
              t('common.selectTextPlaceholder') +
              t('studentPaper.fields.journalName') +
              t('studentPaper.inputTips.journalSwitch')
            "
            @selected="journalSelected"
          />
          <EditInput
            v-else
            v-model="formData.journalName"
            :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.journalName')"
            @input="handleJournalManualInput"
          />
          <el-button v-if="edit" @click="handleSwitchJournal">
            <span v-if="!manualInput">{{ t('studentPaper.inputTips.journalManual') }}</span>
            <span v-else>{{ t('studentPaper.inputTips.journalSelect') }}</span>
          </el-button>
        </div>
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.journalIssn')">
        <EditInput
          v-model="formData.journalIssn"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.journalIssn')"
        />
      </el-descriptions-item>
      <el-descriptions-item
        label-class-name="negative-warning-label"
        class-name="negative-warning-content"
        v-if="formData.negative"
        :label="t('studentPaper.view.warning')"
      >
        <el-alert type="error" :closable="false">{{ formData.negativeMessage }}</el-alert>
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.journalDistrict')">
        <EditInput
          v-model="formData.journalDistrict"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.journalDistrict')"
        />
      </el-descriptions-item>
      <!-- 影响因子 暂时隐藏 -->
      <el-descriptions-item v-if="false" :label="t('studentPaper.fields.journalImpactFactor')">
        <EditInput
          v-model="formData.journalImpactFactor"
          :placeholder="
            t('common.inputTextPlaceholder') + t('studentPaper.fields.journalImpactFactor')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.retrievalStatus')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_RETRIEVAL_STATUS"
          v-model="formData.retrievalStatus"
          :placeholder="
            t('common.selectTextPlaceholder') + t('studentPaper.fields.retrievalStatus')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.publicationStatus')">
        <EditDict
          :dict-type="DICT_TYPE.RESEARCH_PUBLICATION_STATUS"
          v-model="formData.publicationStatus"
          :placeholder="
            t('common.selectTextPlaceholder') + t('studentPaper.fields.publicationStatus')
          "
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已接收'"
        :label="t('studentPaper.fields.acceptanceLetter')"
      >
        <IMRUpload
          v-model="formData.acceptanceLetter"
          :file-type="['pdf']"
          :file-size="20"
          :limit="1"
          :disabled="!edit"
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已接收'"
        :label="t('studentPaper.fields.receiveTime')"
      >
        <EditDate
          v-model="formData.receiveTime"
          :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.receiveTime')"
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已在线'"
        :label="t('studentPaper.fields.retrievalNumber')"
      >
        <EditInput
          v-model="formData.retrievalNumber"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.retrievalNumber')"
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已在线'"
        :label="t('studentPaper.fields.onlineTime')"
      >
        <EditDate
          v-model="formData.onlineTime"
          :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.onlineTime')"
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已发表'"
        :label="t('studentPaper.fields.publicationNumber')"
      >
        <EditInput
          v-model="formData.publicationNumber"
          :placeholder="
            t('common.inputTextPlaceholder') + t('studentPaper.fields.publicationNumber')
          "
          :input-tips="t('studentPaper.inputTips.publicationNumber')"
        />
      </el-descriptions-item>
      <el-descriptions-item
        v-if="formData.publicationStatus === '已发表'"
        :label="t('studentPaper.fields.publishTime')"
      >
        <EditDate
          v-model="formData.publishTime"
          :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.publishTime')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.remark')">
        <EditInput
          v-model="formData.remark"
          type="textarea"
          maxlength="200"
          show-word-limit
          :rows="2"
          :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.remark')"
        />
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.reviewStatus')">
        <el-tag v-if="formData.reviewStatus" type="primary">{{ formData.reviewStatus }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item :label="t('studentPaper.fields.reviewTime')">
        {{ formatDate(formData.reviewTime) }}
      </el-descriptions-item>
    </el-descriptions>

    <template v-if="edit" #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="edit = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
  <StudentPaperAudit ref="auditRef" @success="handleAuditFinish" />
</template>
<script setup lang="ts">
import { StudentPaperApi, StudentPaperVO } from '@/api/core/studentpaper'
import EditInput from '@/views/core/ustcstudent/components/input/EditInput.vue'
import EditDate from '@/views/core/ustcstudent/components/input/EditDate.vue'
import EditDict from '@/views/core/ustcstudent/components/input/EditDict.vue'
import IMRUpload from '@/components/IMRUpload/index.vue'
import { DICT_TYPE } from '@/utils/dict'
import PositiveJournalSelect from '@/views/core/positivejournals/components/PositiveJournalSelect.vue'
import StudentPaperAudit from './StudentPaperAudit.vue'
import { formatDate } from '@/utils/formatTime'
import UserSelect from '@/views/system/user/components/UserSelect.vue'
import { UserVO } from '@/api/system/user'
import { PositiveJournalsApi, PositiveJournalsVO } from '@/api/core/positivejournals'

/** 论文 表单 */
defineOptions({ name: 'StudentPaperForm' })

const edit = ref(false)
provide('editMode', edit)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<Partial<StudentPaperVO>>({})

const auditRef = ref<InstanceType<typeof StudentPaperAudit>>()

/** 打开弹窗 */
const open = async (id: string) => {
  edit.value = false
  dialogVisible.value = true
  formLoading.value = true
  formData.value = {}
  try {
    formData.value = await StudentPaperApi.getStudentPaper(id)
    if (formData.value && !formData.value?.attachment) {
      formData.value.attachment = '[]'
    }
    // 初始化手动输入期刊状态
    manualInput.value = !!(formData.value.journalName && !formData.value.journalId)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StudentPaperVO
    await StudentPaperApi.updateStudentPaper(data)
    message.success(t('common.updateSuccess'))
    edit.value = false
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 选择期刊后自动带入其他字段
const journalSelected = async (item: PositiveJournalsVO) => {
  if (item) {
    formData.value.journalName = item.name
    formData.value.journalImpactFactor = item.impactFactor
    formData.value.journalDistrict = item.district
    formData.value.journalIssn = item.issn
    formData.value.retrievalStatus = 'SCI'

    const response = await PositiveJournalsApi.judgePositiveJournals(item.id)
    formData.value.negative = response.isNegative
    formData.value.negativeMessage = response.message
  } else {
    formData.value.journalName = undefined
    formData.value.journalImpactFactor = undefined
    formData.value.journalDistrict = undefined
    formData.value.journalIssn = undefined
    formData.value.retrievalStatus = undefined

    formData.value.negative = false
    formData.value.negativeMessage = undefined
  }
}

const manualInput = ref(false)
const handleSwitchJournal = () => {
  manualInput.value = !manualInput.value
}

const handleJournalManualInput = () => {
  formData.value.journalId = ''
  formData.value.negative = false
  formData.value.negativeMessage = undefined
}

const handleEdit = () => {
  edit.value = true
}

const handleAudit = () => {
  auditRef.value?.open(formData.value.id!)
}

const handleMentorSelected = (user: UserVO) => {
  formData.value.mentorId = user.id
  formData.value.mentorCode = user.jobCode
  formData.value.mentorName = user.nickname
}

const handleAuditFinish = () => {
  edit.value = false
  dialogVisible.value = false
  emit('success')
}
</script>

<style lang="scss" scoped>
:deep(.negative-warning-label) {
  background: var(--el-color-error-light-9) !important;
  color: var(--el-color-error) !important;
  text-align: center !important;
  font-weight: 700 !important;
}

:deep(.negative-warning-content) {
  padding: 0 !important;
}
</style>
